package com.wfm.niuke;

import com.wfm.common.TreeNode;
import java.util.HashMap;
import java.util.HashSet;

public class LowestCommonAncestorO68 {
    HashMap<Integer,TreeNode> map = new HashMap<>();
    HashSet<Integer> visited = new HashSet<>();
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        while(p!=null){
            visited.add(p.val);
            p = map.get(p.val);
        }
        while(q!=null){
            if(visited.contains(q.val)){
                return q;
            }
            q = map.get(q.val);
        }
        return null;
    }
    public void dfs(TreeNode root){
        if(root.left!=null){
            map.put(root.left.val,root);
            dfs(root.left);
        }
        if(root.right!=null){
            map.put(root.right.val,root);
            dfs(root.right);
        }
    }
}
